<?php


namespace App\Services;



use App\Exceptions\ApiException;
use App\Models\AuthRule;

class AuthRuleService
{
    /**
     * 生成树形权限结点
     * @return array
     */
    public function getTreeList()
    {
        $list = AuthRule::all('id', 'pid', 'name', 'title')->toArray();
        $list = array_column($list, null, 'id');
        return generateTree($list);
    }


    /**
     * 新增路由节点
     * @param $data
     * @throws OperateException
     */
    public function add($data)
    {
        $rule= AuthRule::where('name',$data['name'])->first();
        if (!empty($rule)){
            throw new ApiException(20007);
        }

        $rule= AuthRule::where('title',$data['title'])->first();
        if (!empty($rule)){
            throw new ApiException(20008);
        }

        $authrule = new AuthRule();
        $authrule->pid = $data['pid'];
        $authrule->name = $data['name'];
        $authrule->title = $data['title'];
        $authrule->save();
    }

    /**
     * 修改权限节点
     * @param $data
     * @throws OperateException
     */
    public function edit($data){
        $authrule=AuthRule::find($data['id']);
        if (empty($authrule)){
            throw new ApiException(30001);
        }

        $rule= AuthRule::where('name',$data['name'])
            ->where('id','<>',$data['id'])
            ->first();
        if (!empty($rule)){
            throw new ApiException(20007);
        }

        $rule= AuthRule::where('title',$data['title'])
            ->where('id','<>',$data['id'])
            ->first();
        if (!empty($rule)){
            throw new ApiException(20008);
        }

        $authrule->pid = $data['pid'];
        $authrule->name = $data['name'];
        $authrule->title = $data['title'];
        $authrule->save();

    }

    /**
     * 删除节点
     * @param int $id
     * @throws OperateException
     */
    public function del(int $id){
        $authrule=AuthRule::find($id);
        if (empty($authrule)){
            throw new ApiException(30001);
        }
        $authrule->delete();
    }
}
